package com.slwish.xty.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.slwish.common.base.PresenterToolbarActivity;
import com.slwish.common.interf.PerfectClickListener;
import com.slwish.common.utils.KeyBoardUtils;
import com.slwish.common.utils.LogUtils;
import com.slwish.xty.R;
import com.slwish.xty.adapter.SignAdjustAdapter;
import com.slwish.xty.base.BaseApplication;
import com.slwish.xty.entity.PoiInfoI;
import com.slwish.xty.mvp.contract.SignAdjustContract;
import com.slwish.xty.mvp.presenter.SignAdjustPresenter;
import com.slwish.xty.utils.LocaServiceUtils;
import com.slwish.xty.utils.MapUtils;
import com.slwish.xty.widget.MaterialSearchView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class SignAdjustActivity extends PresenterToolbarActivity<SignAdjustContract.Presenter> implements SignAdjustContract.View {
    @BindView(R.id.mapview)
    MapView mMapView;
    @BindView(R.id.ll_bag)
    LinearLayout ll_bag;
    @BindView(R.id.xrecyclerview)
    XRecyclerView xrecyclerview;
    @BindView(R.id.search_view)
    MaterialSearchView search_view;
    //    @BindView(R.id.et_search)
    EditText etSearch;
    List<PoiInfoI> mList = new ArrayList<>();
    SignAdjustAdapter mAdapter;
    //百度地图相关
    private BaiduMap mBaiduMap;
    //定位Client
    private LocationClient mLocClient;
    private int mCurrentDirection = 0;//方向信息
    private double mCurrentLat = 0.0;//纬度
    private double mCurrentLon = 0.0;//经度
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;//LocationData
    private float mCurrentAccracy;
    private BitmapDescriptor mCurrentMarker;//自定义位置Marker
    private PoiSearch mPoiSearch;//Poi检索
    private String city;//当前定位城市
    private String address;
    private LatLng latLng;
    List<PoiInfoI> mSearchList = new ArrayList<>();
    private PoiInfoI checkPosiModel;

    @Override
    protected int getLayoutId() {
        return R.layout.act_sign_adjust;
    }

    @SuppressLint("ResourceType")
    @Override
    protected void initWidget() {
        super.initWidget();
        setTitle(R.string.sign_adjust_title);
        setRightText(R.string.comfirm_text);
        setLeftText(R.string.cancel_text);
        etSearch = search_view.getSearchEditText();
        city = getIntent().getStringExtra("CITY");
        address = getIntent().getStringExtra("ADDRESS");
        xrecyclerview.setLayoutManager();
        xrecyclerview.setLoadingMoreEnabled(false);
        xrecyclerview.setPullRefreshEnabled(false);
        mAdapter = new SignAdjustAdapter(mList);
        xrecyclerview.setAdapter(mAdapter);
//        initPop();
        initBaiduMap();

        setLeftOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });

        setRightOnClickListener(new PerfectClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {

                Intent intent = new Intent();
                intent.putExtra("MODEL", checkPosiModel);
                setResult(100, intent);
                finish();
            }
        });
    }

    int prePos = 0;

    @Override
    protected void initEvent() {
        super.initEvent();
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                position = position - 1;
                checkPosiModel = mAdapter.getItem(position);
                checkPosiModel.setCheck(!checkPosiModel.isCheck());
                if (prePos != position) {
                    mAdapter.getItem(prePos).setCheck(false);
                } else {
                    checkPosiModel.setCheck(true);
                }
                mAdapter.notifyDataSetChanged();
                prePos = position;
                MapUtils.getMarkerAndMove(mBaiduMap, mAdapter.getItem(position).location, R.mipmap.dtdw);
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //隐藏键盘
                    KeyBoardUtils.hideKeyBoard(mContext, v);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mPoiSearch.searchInCity((new PoiCitySearchOption())
                                    .city(city)
                                    .keyword(etSearch.getText().toString())
                                    .pageNum(10));
                        }
                    }, 500);

                    return true;
                }
                return false;
            }
        });
        /**
         * 搜索框
         */
        search_view.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public void onItemClick(PoiInfoI model) {
                checkPosiModel = model;
                mList.clear();
                mList.add(model);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected SignAdjustContract.Presenter initPresenter() {
        return new SignAdjustPresenter(this);
    }

    /**
     * 初始化百度地图
     */
    private void initBaiduMap() {
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
//        mBaiduMap.setMyLocationEnabled(true);
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(poiListener);
        // 定位初始化
        LocaServiceUtils locaServiceUtils = BaseApplication.getLocaService();
        locaServiceUtils.registerListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(final BDLocation location) {
                // map view 销毁后不在处理新接收的位置
                if (location == null || mMapView == null) {
                    return;
                }
                city = location.getCity();
                locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(mCurrentDirection).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                if (isFirstLoc) {
                    isFirstLoc = false;
                    latLng = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    MapUtils.getMarkerAndMove(mBaiduMap, latLng, R.mipmap.dtdw);
//                    MapStatus.Builder builder = new MapStatus.Builder();
//                    builder.target(latLng).zoom(18.0f);
//                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                }

            }
        });
        locaServiceUtils.start();
        mLocClient = locaServiceUtils.getLocationClient();

        // 修改为自定义marker
//        mCurrentMarker = BitmapDescriptorFactory
//                .fromResource(R.mipmap.dtdwss);
//        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
//                MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));
        if (!TextUtils.equals(address, ""))
            mPoiSearch.searchInCity(new PoiCitySearchOption()
                    .city(city)
                    .keyword(address)
                    .pageNum(10));

    }

    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener() {

        public void onGetPoiResult(PoiResult result) {
            if (!TextUtils.equals(etSearch.getText().toString(), "")) {
                if (result != null) {
                    mSearchList.clear();
                    if (result.getAllPoi() != null) {
                        for (PoiInfo model : result.getAllPoi()) {
                            PoiInfoI poiInfoI = new PoiInfoI();
                            poiInfoI.name = model.name;
                            poiInfoI.address = model.address;
                            poiInfoI.city = model.city;
                            poiInfoI.phoneNum = model.phoneNum;
                            poiInfoI.isPano = model.isPano;
                            poiInfoI.location = model.location;
                            poiInfoI.postCode = model.postCode;
                            poiInfoI.type = model.type;
                            mSearchList.add(poiInfoI);
                        }
                    } else {
                        mSearchList.addAll(new ArrayList<PoiInfoI>());
                    }
                    search_view.setSuggestions(mSearchList);
//                    mAdapter.notifyDataSetChanged();
                }
                //获取POI检索结果
            } else {
                if (result != null && result.getAllPoi() != null) {
                    mList.clear();
                    for (PoiInfo model : result.getAllPoi()) {
                        PoiInfoI poiInfoI = new PoiInfoI();
                        poiInfoI.name = model.name;
                        poiInfoI.address = model.address;
                        poiInfoI.city = model.city;
                        poiInfoI.phoneNum = model.phoneNum;
                        poiInfoI.isPano = model.isPano;
                        poiInfoI.location = model.location;
                        poiInfoI.postCode = model.postCode;
                        poiInfoI.type = model.type;
                        mList.add(poiInfoI);
                    }
                    mAdapter.notifyDataSetChanged();
                }
            }
        }

        public void onGetPoiDetailResult(PoiDetailResult result) {
            //获取Place详情页检索结果
//            LogUtils.i("xx", "PoiDetailResult:" + result.toString());
        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {
            LogUtils.i("xx", "PoiIndoorResult:" + poiIndoorResult.toString());

        }
    };

    @OnClick({R.id.iv_location})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_location:
                // 移动到当前位置
                MapUtils.getMarkerAndMove(mBaiduMap, latLng, R.mipmap.dtdw);
                break;
        }
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
        //为系统的方向传感器注册监听器
//        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
//                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onStop() {
        //取消注册传感器监听
//        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        if (mLocClient != null)
            mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        if (mPoiSearch != null)
            mPoiSearch.destroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (search_view.isSearchOpen()) {
            search_view.closeSearch();
        } else {
            super.onBackPressed();
        }

    }
}
